package model

import (
	"fmt"
	"github.com/xormplus/xorm"
	"time"
)

type (
	ProductModel interface {
		Insert(data *Product) (int64, error)
		FindOne(id int64) (*Product, error)
		Update(data *Product) error
		Delete(id int64) error
	}

	defaultProductModel struct {
		Engine *xorm.Engine
		table  string
	}

	Product struct {
		Id         int64
		Name       string    `xorm:"varchar(32)"` // 产品名称
		Desc       string    // 产品描述
		Stock      int64     // 产品库存
		Amount     int64     // 产品金额
		Status     int64     // 产品状态
		CreateTime time.Time `xorm:"created"`
		UpdateTime time.Time `xorm:"updated"`
	}
)

func NewProductModel(engine *xorm.Engine) ProductModel {
	return &defaultProductModel{
		Engine: engine,
		table:  "`product`",
	}
}

func (m *defaultProductModel) Insert(data *Product) (int64, error) {
	//sql_7:=m.Engine.GetSql("sql_7_1")
	//affected, err := m.Engine.SQL(sql_7, data.Name, data.Desc,data.Stock,data.Amount,data.Status).Execute()
	affected, err := m.Engine.Insert(data)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("[Test_Sql_Execute]->rows:\n", affected)
	return affected, err
}

func (m *defaultProductModel) FindOne(id int64) (*Product, error) {
	sql1 := m.Engine.GetSql("sql_1_1")
	var resp Product
	//select * from produt where id = ?
	has, err := m.Engine.SQL(sql1, id).Get(&resp)
	if err != nil {
		fmt.Println(err)
	}
	if !has {
		fmt.Println("[Test_Get_Struct]->rows: not exist\n")
	}
	fmt.Println("[Test_Get_Struct]->rows:\n", resp)
	return &resp, nil
}

func (m *defaultProductModel) Update(data *Product) error {
	sql_72 := m.Engine.GetSql("sql_id_7_2")
	affected, err := m.Engine.SQL(sql_72, data.Amount, data.Name).Execute()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(affected)
	return err
}

func (m *defaultProductModel) Delete(id int64) error {
	sql_7 := m.Engine.GetSql("sql_id_7_3")
	affected, err := m.Engine.SQL(sql_7, id).Execute()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("[Test_Sql_Execute]->rows:\n", affected)
	return err
}

